<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>宣讲类别管理</span>
      </div>
    </template>

    <div class="search-form">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" @submit.native.prevent="() => onSubmit">
        <el-form-item>
          <el-input v-model="formInline.typeName" placeholder="请输入宣讲分类名称" clearable @keyup.enter="onSubmit"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="addType">新建</el-button>
      </div>
    </div>

    <div class="table-data" v-loading="loading">
      <el-table
        :data="typeData"
        stripe
        borderresizable
        highlight-hover-row
        show-overflow
        keep-source
        scrollbar-always-on
      >
        <el-table-column
          v-for="(tableItem, tableIndex) in typeTableColumns" :key="tableIndex"
          :prop="tableItem.field"
          :label="tableItem.label"
          :min-width="tableItem.minWidth"
          :formatter="tableItem.formatter"
          :show-overflow-tooltip="tableItem.field != 'coverUrl'"
        >
        </el-table-column>
        <el-table-column
          fixed="right"
          field="opera"
          label="操作"
          min-width="180"
        >
          <template #default="{ row }">
            <el-button
              type="warning"
              link
              @click="typeDelete(row)"
            >删除</el-button>
            <el-button
              type="success"
              link
              @click="addSubmitted(row)"
              v-if="isFilling"
            >新增宣讲报送</el-button>
            <el-button
              type="success"
              link
              @click="typeEdit(row)"
            >编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-page">
        <el-pagination background layout="prev, pager, next" :total="dataTotal" :page-size="pageSize" :current-page="currentPage" @current-change="currentChange" />
      </div>
    </div>

    <!-- 新增、编辑宣讲队成员弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="宣讲类别">
      <el-form :model="typeForm" ref="typeFormRef" label-width="120px" :rules="typeRules">
        <el-form-item label="宣讲类别名称" prop="typeName">
          <el-input v-model="typeForm.typeName" placeholder="请输入宣讲类别名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitType">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

  </el-card>
</template>
<script>
export default { name: 'backendPublicizetype' }
</script>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { http } from '@/utils/http/index';
import { ContentTypeEnum } from '@/enums/httpEnum';
import { useAuthStore } from '@/stores/modules/auth.js';

/* 路由 */
const route = useRouter();

/* 用户信息 */
const authStore = useAuthStore()

/* 当前用户是否具备学习上报权限 */
const isFilling = computed(() => { 
  let actions = authStore.userInfo.actions
  if(!actions) return
  const find = actions.find(item => item.id == '2.1')
  return find ? true : false
})


onMounted(() => {
  onSubmit()
})

/* 搜索表单 */
const formInline = ref({
  typeName: "",
})

/* 分页 */
const dataTotal = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

/* 切换页码方法 */
const currentChange = (val) => {
  currentPage.value = val
  onSubmit()
}

/* 表格数据加载动画 */
const loading = ref(false)

/* 表格数据 */
const typeData = ref([])

/* 表格字段 */
const typeTableColumns = reactive([
  { field: "typeName", label: "宣讲类别名称", minWidth: "180" }
])

/* 列表筛选 */
const onSubmit = () => {
  loading.value = true
  let params = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
  }
  let dfi = {
    Logic: 0,
    Filters: []
  }

  for (let k in formInline.value){
    if(formInline.value[k]){
      dfi.Filters.push({
        Field: k,
        Operator: 0,
        Value: formInline.value[k]
      })
    }
  }

  if(dfi.Filters.length){
    params.dfi = dfi
  }
  http.$POST("/PreachM/GetPreachFillingTypeInfoList", params).then(res => {
    loading.value = false
    if (res.isError) return
    typeData.value = res.result.dataLst
    dataTotal.value = res.result.countAll
  }).catch(err => {
    loading.value = false
    ElMessage.warning("查询失败，请重试")
  })
}

/* 新增 */
const dialogFormVisible = ref(false)
const typeFormRef = ref(null)
const typeForm = ref({
  typeName: ""
})
const typeRules = ref({
  typeName: [
    { required: true, message: '请输入宣讲类别名称', trigger: 'blur' },
    { max: 255, message: '不能输入超过255个字符', trigger: 'blur'}
  ],
})

/* 点击新增宣讲类别 */
const addType = () => {
  dialogFormVisible.value = true;
  if(typeForm.value.id) {
    delete typeForm.value.id
  }
}

/* 点击编辑宣讲类别按钮 */
const typeEdit = (row) => {
  dialogFormVisible.value = true
  http.$GET(`/PreachM/GetPreachFillingTypeDetailById?Id=${row.id}`).then(res => {
    if(res.isError) return
    if (!res.result) return
    /* 赋值 */
    Object.keys(typeForm.value).forEach((key)=>{
      if(res.result[key] != null){
        typeForm.value[key] = res.result[key];
      }
    })
    typeForm.value.id = res.result.id
  }).catch(err => {
    ElMessage.warning("查询失败")
  })
}

/* 点击确定 */
const submitType = () => {
  typeFormRef.value.validate((valid, fields) => {
    if(valid) {
      http.$POST("/PreachM/AddOrUpdatePreachFillingTypeInfo", {...typeForm.value}, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
        if (res.IsError) {
          ElMessage.warning('操作失败');
        }else {
          ElMessage.success('操作成功');
          typeFormRef.value.resetFields()
          dialogFormVisible.value = false
          onSubmit()
        }
      }).catch(err => {
        ElMessage.warning('操作失败');
      })
    }else {
      ElMessage.warning("请先完成必填项")
    }
  })
}

/* 点击删除课程分类 */
const typeDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除此条数据吗？',
    '请确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    http.$POST(`/PreachM/DelPreachFillingTypeById?Id=${row.id}`).then(res => {
      if(res.IsError) {
        ElMessage.warning("操作失败")
      }else {
        ElMessage.success("操作成功")
        dialogFormVisible.value = false
        onSubmit()
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消删除',
    })
  })
}

/* 点击跳转新建课程 */
const addSubmitted = (row) => {
  route.push({
    path: "/backend/publicize-submitted/add",
    query: { type: 'add', typeId: row.id }
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>